local function OnSave(inst, data)
	data.all_treasure_count = inst.all_treasure_count
	data.found_treasure_count = inst.found_treasure_count
	data.playerdata = inst.playerdata
end

local function OnLoad(inst, data)
	if data ~= nil then
		inst.all_treasure_count = data.all_treasure_count
		inst.found_treasure_count = data.found_treasure_count
		inst.playerdata = data.playerdata
	end
end

local function fn()
	local inst = CreateEntity()

	inst.entity:AddTransform()
	inst.entity:AddNetwork()
	inst.entity:SetPristine()

	if not TheWorld.ismastersim then
		return inst
	end

	inst.all_treasure_count = 0
	inst.found_treasure_count = 0
	inst.playerdata = {}

	TheWorld.Musha_Watcher = inst

	inst:ListenForEvent(
		"ms_newplayercharacterspawned",
		function(world, data)
			if data and data.player then
				local character = data.player

				if not inst.playerdata[character.userid] then
					inst.playerdata[character.userid] = {}
					inst.playerdata[character.userid] = {}
					inst.playerdata[character.userid].skills = {}
					inst.playerdata[character.userid].followers = {}
				end
				if character.components.musha_skills then
					local skill_data = inst.playerdata[character.userid].skills
					if next(skill_data) ~= nil then
						character.components.musha_skills.data = skill_data
					else
					end
				end
				if character.components.musha_leader then
					local follower_data = inst.playerdata[character.userid].followers
					if next(follower_data) ~= nil then
						character.components.musha_leader.followers = follower_data
					end
				end
			end
		end,
		TheWorld
	)
	inst:ListenForEvent(
		"ms_playerdespawn",
		function(world, player)
			if player.components.musha_skills then
				for k, v in pairs(player.components.musha_skills.skill_point) do
					inst.playerdata[player.userid].skills[k] = v:value()
				end
			end
			if player.components.musha_leader and player.components.musha_leader.followers then
				for name, entity in pairs(player.components.musha_leader.followers) do
					entity:DoTaskInTime(
						0,
						function(entity)
							if entity and entity:IsValid() then
								entity:Remove()
							end
						end
					)
				end
			end
		end,
		TheWorld
	)

	inst.OnSave = OnSave
	inst.OnLoad = OnLoad

	musha_print("Musha_Watcher Spawned")

	return inst
end

return Prefab("musha_watcher", fn, nil, nil)
